const log = require('../../util/log')
const config = require('../../util/config')
const logger = require('log4js').getLogger()

async function getJdAdvLink(obj) {
  try {
    const {
      Network,
      Page,
      DOM,
      Runtime,
      Emulation
    } = this.client;
    obj = obj || {}
    obj.times = (obj.times || 0) + 1
    if (!obj.link) {
      return new Promise((resolve, reject) => {
        reject('缺少link')
      })
    }
    if (obj.step !== 0) {
      logger.debug('[' + __filename + ':' + __line + ']', 'getting jd advertising link')
      obj.step = 0
    }
    if (!obj.link.match(/\d+.html/i)) {
      return new Promise((resolve, reject) => {
        reject('link不合法')
      })
    }
    var skuId = obj.link.match(/\d+.html/i)[0]
    skuId = skuId.substring(0, skuId.length - 5)
    return new Promise((resolve, reject) => {
      this.getJdItems({
        keyword: skuId
      }).then(result => {
        if (result.length == 0) {
          reject('该商品不能返利')
          return
        }
        step2.call(this, obj).then(result => {
          resolve(result)
        }, result => {
          reject(result)
        })
      }, result => {
        reject(result)
      })
    })
  } catch (err) {
    log(err)
  }
}

async function step2(obj) {
  try {
    obj.times++
      if (obj.times >= config.chromeMaxTimes) {
        return new Promise((resolve, reject) => {
          reject('系统错误')
        })
      }
    const {
      Network,
      Page,
      DOM,
      Runtime,
      Emulation
    } = this.client
    if (obj.step !== 2) {
      logger.debug('[' + __filename + ':' + __line + ']', 'getting jd advertising link step 2')
      obj.step = 2
    }
    // Page.navigate({
    //   url: 'https://media.jd.com/gotoadv/customPromotion'
    // })
    for (var i = 1; i < 20; i++) {
      var {
        result
      } = await Runtime.evaluate({
        expression: 'document.querySelectorAll("#sidebar a")[' + i + '].innerText'
      })
      if (result.value == '自定义链接推广') {
        await Runtime.evaluate({
          expression: 'document.querySelectorAll("#sidebar a")[' + i + '].click();'
        })
        break
      }
    }
    return step2_5.call(this, obj)
  } catch (err) {
    log(err)
  }
}

async function step2_5(obj) {
  try {
    obj.times++
      if (obj.times >= config.chromeMaxTimes) {
        return new Promise((resolve, reject) => {
          reject('系统错误')
        })
      }
    const {
      Network,
      Page,
      DOM,
      Runtime,
      Emulation
    } = this.client
    if (obj.step !== 2.5) {
      logger.debug('[' + __filename + ':' + __line + ']', 'getting jd advertising link step 2.5')
      obj.step = 2.5
    }
    var {
      result
    } = await Runtime.evaluate({
      expression: 'location.href'
    })
    if (result.value == 'https://media.jd.com/gotoadv/customPromotion') {
      await Runtime.evaluate({
        expression: 'window.alert=()=>{}'
      })
      return step3.call(this, obj)
    }
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        step2_5.call(this, obj).then(result => {
          resolve(result)
        }, result => {
          reject(result)
        })
      }, 1000)
    })
  } catch (err) {
    log(err)
  }
}

async function step3(obj) {
  try {
    obj.times++
      if (obj.times >= config.chromeMaxTimes) {
        return new Promise((resolve, reject) => {
          reject('系统错误')
        })
      }
    const {
      Network,
      Page,
      DOM,
      Runtime,
      Emulation
    } = this.client
    if (obj.step !== 3) {
      logger.debug('[' + __filename + ':' + __line + ']', 'getting jd advertising link step 3')
      obj.step = 3
    }
    var {
      result
    } = await Runtime.evaluate({
      expression: 'document.querySelectorAll("#targetCode").length'
    })
    if (result.value == 1) {
      var {
        result
      } = await Runtime.evaluate({
        expression: 'document.querySelectorAll("#targetCode")[0].value'
      })
      if (result.value != '') {
        return new Promise(resolve => {
          resolve({
            advLink: result.value
          })
        })
      }
    }
    var {
      result
    } = await Runtime.evaluate({
      expression: 'document.querySelectorAll("#unionWebId").length'
    })
    if (result.value == 0) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          step3.call(this, obj).then(result => {
            resolve(result)
          }, result => {
            reject(result)
          })
        }, 1000)
      })
    }
    var {
      result
    } = await Runtime.evaluate({
      expression: 'document.querySelectorAll("#spaceName").length'
    })
    if (result.value == 0) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          step3.call(this, obj).then(result => {
            resolve(result)
          }, result => {
            reject(result)
          })
        }, 1000)
      })
    }
    await Runtime.evaluate({
      expression: 'document.querySelectorAll("#protocol_2")[0].checked=true'
    })
    await Runtime.evaluate({
      expression: 'document.querySelectorAll("#unionWebId")[0].value="1015309151"'
    })
    await Runtime.evaluate({
      expression: 'document.querySelectorAll("#spaceName")[0].value="1015370944"'
    })
    await Runtime.evaluate({
      expression: 'document.querySelectorAll("#urlArea")[0].value="' + obj.link + '"'
    })
    var {
      result
    } = await Runtime.evaluate({
      expression: 'document.querySelectorAll(".red-btn")'
    })
    var cnt = result.description.substring(9, result.description.length - 1)
    if (cnt == 0) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          step3.call(this, obj).then(result => {
            resolve(result)
          }, result => {
            reject(result)
          })
        }, 1000)
      })
    }
    if (cnt > 1) {
      return new Promise((resolve, reject) => {
        reject('按钮多于1个')
      })
    }
    await Runtime.evaluate({
      expression: 'document.querySelectorAll(".red-btn")[0].click()'
    })
    return new Promise(resolve => {
      setTimeout(() => {
        step3.call(this, obj).then(result => {
          resolve(result)
        }, result => {
          reject(result)
        })
      }, 1000)
    })
  } catch (err) {
    log(err)
  }
}

module.exports = getJdAdvLink